package com.abc.recycling.controller;

import com.abc.recycling.model.Order;
import com.abc.recycling.model.User;
import com.abc.recycling.service.CollectorOrderService;
import com.abc.recycling.service.UserService;
import com.abc.recycling.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.Data;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Slf4j
@Controller
@RequestMapping("/collector/orders")
@RequiredArgsConstructor
public class CollectorOrderController {

    private final UserService userService;
    private final CollectorOrderService collectorOrderService;

    /**
     * 待处理订单列表页
     */
    @GetMapping("/pending")
    public String getPendingOrders(Authentication authentication, Model model) {
        try {
            log.info("获取待处理订单列表");
            User collector = userService.getUserByUsername(authentication.getName());
            PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> orders = collectorOrderService.getOrdersByStatus("PENDING", pageRequest);
            
            // 获取订单关联的用户信息
            Map<Long, User> userMap = new HashMap<>();
            for (Order order : orders.getContent()) {
                User user = userService.getUserById(order.getUserId());
                if (user != null) {
                    userMap.put(order.getUserId(), user);
                }
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("userMap", userMap);
            log.debug("待处理订单数: {}", orders.getTotalElements());
            return "collector/orders/pending";
        } catch (Exception e) {
            log.error("获取待处理订单失败", e);
            throw e;
        }
    }

    /**
     * 待处理订单列表（仅内容部分）
     */
    @GetMapping("/pending/list")
    public String getPendingOrdersList(Authentication authentication, Model model) {
        try {
            // 获取当前登录的回收员信息
            User collector = userService.getUserByUsername(authentication.getName());
            
            // 获取所有待处理订单列表
            PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> ordersPage = collectorOrderService.getOrdersByCollectorAndStatus(collector.getId(), "PENDING", pageRequest);
            List<Order> orders = ordersPage.getContent();
            
            // 获取订单关联的用户信息
            Map<Long, User> userMap = new HashMap<>();
            for (Order order : orders) {
                User user = userService.getUserById(order.getUserId());
                if (user != null) {
                    userMap.put(order.getId(), user);
                }
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("userMap", userMap);
            return "collector/orders/pending :: orderList";
        } catch (Exception e) {
            log.error("获取待处理订单列表失败", e);
            throw e;
        }
    }

    /**
     * 进行中订单列表页
     */
    @GetMapping("/processing")
    public String getProcessingOrders(Authentication authentication, Model model) {
        try {
            log.info("获取进行中订单列表");
            User collector = userService.getUserByUsername(authentication.getName());
            PageRequest pageRequest = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> orders = collectorOrderService.getOrdersByCollectorAndStatus(collector.getId(), "PROCESSING", pageRequest);
            
            // 获取订单关联的用户信息
            Map<Long, User> userMap = new HashMap<>();
            for (Order order : orders.getContent()) {
                User user = userService.getUserById(order.getUserId());
                if (user != null) {
                    userMap.put(order.getUserId(), user);
                }
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("userMap", userMap);
            log.debug("进行中订单数: {}", orders.getTotalElements());
            return "collector/orders/processing";
        } catch (Exception e) {
            log.error("获取进行中订单失败", e);
            throw e;
        }
    }

    /**
     * 已完成订单列表页
     */
    @GetMapping("/completed")
    public String getCompletedOrders(Authentication authentication, Model model) {
        try {
            log.info("获取已完成订单列表");
            User collector = userService.getUserByUsername(authentication.getName());
            // 使用一个足够大的页面大小来获取所有订单
            PageRequest pageRequest = PageRequest.of(0, Integer.MAX_VALUE, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> orders = collectorOrderService.getOrdersByCollectorAndStatus(collector.getId(), "COMPLETED", pageRequest);
            
            // 获取订单关联的用户信息
            Map<Long, User> userMap = new HashMap<>();
            for (Order order : orders.getContent()) {
                User user = userService.getUserById(order.getUserId());
                if (user != null) {
                    userMap.put(order.getUserId(), user);
                }
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("userMap", userMap);
            log.debug("已完成订单数: {}", orders.getTotalElements());
            return "collector/orders/completed";
        } catch (Exception e) {
            log.error("获取已完成订单失败", e);
            throw e;
        }
    }

    /**
     * 已完成订单列表（仅内容部分）
     */
    @GetMapping("/completed/list")
    public String getCompletedOrdersList(Authentication authentication, Model model) {
        try {
            // 获取当前登录的回收员信息
            User collector = userService.getUserByUsername(authentication.getName());
            
            // 获取所有已完成订单列表
            PageRequest pageRequest = PageRequest.of(0, Integer.MAX_VALUE, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> orders = collectorOrderService.getOrdersByCollectorAndStatus(collector.getId(), "COMPLETED", pageRequest);
            
            // 获取订单关联的用户信息
            Map<Long, User> userMap = new HashMap<>();
            for (Order order : orders.getContent()) {
                User user = userService.getUserById(order.getUserId());
                if (user != null) {
                    userMap.put(order.getUserId(), user);
                }
            }
            
            model.addAttribute("orders", orders);
            model.addAttribute("userMap", userMap);
            return "collector/orders/completed :: orderList";
        } catch (Exception e) {
            log.error("获取已完成订单列表失败", e);
            throw e;
        }
    }

    @PostMapping("/accept/{orderId}")
    @ResponseBody
    public ResponseEntity<?> acceptOrder(@PathVariable Long orderId, Authentication authentication) {
        try {
            log.info("接受订单请求, orderId={}", orderId);
            User collector = userService.getUserByUsername(authentication.getName());
            boolean success = collectorOrderService.acceptOrder(orderId, collector.getId());
            
            if (success) {
                log.info("订单接受成功");
                return ResponseEntity.ok().build();
            } else {
                log.warn("订单接受失败，订单可能已被接受或状态已改变");
                return ResponseEntity.badRequest().body("订单接受失败，订单可能已被接受或状态已改变");
            }
        } catch (Exception e) {
            log.error("接受订单失败", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/complete/{orderId}")
    @ResponseBody
    public Result<?> completeOrder(
            @PathVariable Long orderId,
            @RequestBody CompleteOrderRequest request,
            Authentication authentication) {
        try {
            log.info("完成订单请求, orderId={}", orderId);
            User collector = userService.getUserByUsername(authentication.getName());
            boolean success = collectorOrderService.completeOrder(
                orderId, 
                collector.getId(),
                request.getActualWeight(),
                request.getPrice()
            );
            
            if (success) {
                log.info("订单完成成功");
                return Result.success();
            } else {
                log.warn("完成订单失败，订单可能已被完成或状态已改变");
                return Result.error("完成订单失败，订单可能已被完成或状态已改变");
            }
        } catch (Exception e) {
            log.error("完成订单失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/status/{status}")
    @ResponseBody
    public Page<Order> getOrdersByStatus(
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            log.info("获取订单列表, status={}, page={}, size={}", status, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            User collector = userService.getUserByUsername(authentication.getName());
            return collectorOrderService.getOrdersByCollectorAndStatus(collector.getId(), status, pageRequest);
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            throw e;
        }
    }
    
    @GetMapping("/{collectorId}/status/{status}")
    @ResponseBody
    public Page<Order> getOrdersByCollectorAndStatus(
            @PathVariable Long collectorId,
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取回收员订单列表, collectorId={}, status={}, page={}, size={}", 
                    collectorId, status, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            return collectorOrderService.getOrdersByCollectorAndStatus(collectorId, status, pageRequest);
        } catch (Exception e) {
            log.error("获取回收员订单列表失败", e);
            throw e;
        }
    }

    @Data
    public static class CompleteOrderRequest {
        private Double actualWeight;
        private Double price;
    }
} 